<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\lib\exception\BaseException;
use app\model\Warehouse;
use app\model\Warehousing as WarehousingModel;
use app\model\WarehousingDetails;
use think\facade\Db;

class Warehousing extends BaseController
{
    public function index($limit = 10)
    {
        $name = request()->param('name');
        $status = request()->param('status',1);
        $time = request()->param('time');
        $school = request()->param('school_id');
        $data = WarehousingModel::with(['school', 'supplier', 'detail.product'])
            ->where('school_id', $school)->where('status',$status)
            ->when($name, function ($query) use ($name) {
                $query->where('number', 'like', "%$name%");
            })->when($status, function ($query) use ($status) {
                $query->where('status', $status);
            })->when($time, function ($query) use ($time) {
                $query->whereBetween('create_time', $time);
            })->order('id','desc')->paginate($limit);

        return $this->success($data);
    }

    public function create()
    {
        $params = request()->param();

        Db::startTrans();
        try {

            foreach ($params['data'] as $item) {

                $wid = WarehousingModel::create([
                    'school_id' => $item['school_id'],
                    'remark' => $params['remark'] ?? '',
                    'supplier_id' => $params['supplier_id'],
                    'number' => getNumber('倉庫')
                ]);

                if (empty($item['product'])) {
                    throw new \Exception('入倉請至少選擇一個產品！');
                } else {
                    $details = json_decode($item['product'], true);

                    foreach ($details as $v) {
                        WarehousingDetails::create([
                            'warehousing_id' => $wid->id,
                            'product_id' => $v['product_id'],
                            'num' => $v['num'],
                            'price' => $v['price'],
                            'remark' => $v['remark'] ?? ''
                        ]);

                        $warehouse = Warehouse::where('school_id', $item['school_id'])->where('product_id', $v['product_id'])->find();
                        if (!$warehouse) {
                            Warehouse::create([
                                'school_id' => $item['school_id'],
                                'product_id' => $v['product_id'],
                                'num' => $v['num'],
                                'points_num' => $v['num']
                            ]);

                        } else {
                            $number = $v['num'] + $warehouse->num;
                            $warehouse::where('id', $warehouse->id)->update(['num' => $number, 'points_num' => $number]);
                        }
                    }
                }

            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw  new BaseException(['msg' => $e->getMessage()]);
        }
        return $this->success();

    }

    public function update($id)
    {
        $params = request()->param();

        Db::startTrans();
         WarehousingModel::update([
            'remark' => $params['remark'] ?? '',
            'supplier_id' => $params['supplier_id'],
        ],['id'=>$id]);

        WarehousingDetails::where('warehousing_id',$id)->delete();
        try {

                if (empty($params['product'])) {
                    throw new \Exception('入倉請至少選擇一個產品！');
                } else {

                    foreach ($params['product'] as $v) {
                        WarehousingDetails::create([
                            'warehousing_id' => $id,
                            'product_id' => $v['product_id'],
                            'num' => $v['num'],
                            'price' => $v['price'],
                            'remark' => $v['remark'] ?? ''
                        ]);

                        $warehouse = Warehouse::where('school_id', $params['school_id'])->where('product_id', $v['product_id'])->where('status', '<>', -1)->find();
                        if (!$warehouse) {
                            Warehouse::create([
                                'school_id' => $params['school_id'],
                                'product_id' => $v['product_id'],
                                'num' => $v['num'],
                                'points_num' => $v['num']
                            ]);

                        } else {
                            $number = $v['num'] + $warehouse->num;
                            $warehouse::where('id', $warehouse->id)->update(['num' => $number, 'points_num' => $number]);
                        }
                    }
                }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw  new BaseException(['msg' => $e->getMessage()]);
        }
        return $this->success();

    }

    public function delete($id)
    {
        WarehousingModel::where('id','in',$id)->update(['status'=>-1]);
        return $this->success();
    }

    public function derive($limit=15)
    {

        $status = request()->param('status',1);
        $school = request()->param('school_id');
        $num=request()->param('num');  //1<0 ,2=0,3>0
        $data=WarehousingModel::alias('w')
            ->join('warehousing_details wd','w.id=wd.warehousing_id','left')
            ->join('products p','p.id=wd.product_id','left')
            ->join('school s','s.id=w.school_id','left')
            ->when($status,function ($query) use($status){
                $query->where('p.status',$status);
            })
            ->when($school,function ($query) use($school){
                $query->whereIn('w.school_id',$school);
            })
            ->when($num,function ($query) use($num){
                if($num==1){
                    $query->where('wd.num','<',0);
                }elseif ($num==2){
                    $query->where('wd.num',0);
                }else{
                    $query->where('wd.num','>',0);
                }

            })
            ->field('wd.*,p.name,p.number,p.price,s.name school_name')
            ->paginate($limit);

        return $this->success($data);
    }

    public function inventory($limit=15)
    {

        $status = request()->param('status');
        $school = request()->param('school_id');
        $type= request()->param('type');
        $data=WarehousingModel::alias('w')
            ->join('warehousing_details wd','w.id=wd.warehousing_id','left')
            ->join('products p','p.id=wd.product_id','left')
            ->join('school s','s.id=w.school_id','left')
            ->when($status,function ($query) use($status){
                $query->where('p.status',$status);
            })
            ->when($school,function ($query) use($school){
                $query->whereIn('w.school_id',$school);
            })
            ->when($type,function ($query) use($type){
                $query->whereIn('p.products_type_id',$type);

            })
            ->field('wd.*,p.name,p.number,p.price,s.name school_name,p.safety')
            ->order('s.id','desc')
            ->paginate($limit)->toArray();
        $subtotal = ['num' => 0, 'safety' => 0, 'difference' => 0];
            foreach ($data['data'] as $k=>&$v) {
                $v['difference'] = $v['safety'] - $v['num'];
                $subtotal['num']+=$v['num'];
                $subtotal['safety']+=$v['safety'];
                $subtotal['difference']+=$v['difference'];
            }
            $data['to']=$subtotal;
        return $this->success($data);
    }

    public function top($limit=15)
    {

        $status = request()->param('status');
        $school = request()->param('school_id');
        $type= request()->param('type');
        $data=WarehousingModel::alias('w')
            ->join('warehousing_details wd','w.id=wd.warehousing_id','left')
            ->join('products p','p.id=wd.product_id','left')
            ->join('school s','s.id=w.school_id','left')
            ->when($status,function ($query) use($status){
                $query->where('p.status',$status);
            })
            ->when($school,function ($query) use($school){
                $query->whereIn('w.school_id',$school);
            })
            ->when($type,function ($query) use($type){
                $query->whereIn('p.products_type_id',$type);

            })
            ->field('wd.*,p.name,p.number,p.price,s.name school_name,p.safety')
            ->order('wd.num','desc')
            ->paginate($limit)->toArray();

        return $this->success($data);
    }
}
